package com.palm.hubo2o;

import android.app.Activity;
import android.app.Application;
import android.support.annotation.Nullable;

import com.palm.hubo2o.network.PalmSession;
import com.palm.palmutils.Settings;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by wongqi on 16/6/7.
 */
public class PalmApplication extends Application implements Thread.UncaughtExceptionHandler {
    private final List<Activity> mActivityList = new ArrayList<>();
    private final List<Integer> mHashCodeList = new ArrayList<>();

    private Thread.UncaughtExceptionHandler mDefaultHandler;

    @Override
    public void onCreate() {
        // Prepare to catch crash
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        super.onCreate();
        Settings.init(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(thread, ex);
        }

        Activity activity = getTopActivity();
        if (activity != null) {
            activity.finish();
        }
        PalmSession.logout();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        try {
            ex.printStackTrace();
//            Crash.saveCrashInfo2File(this, ex);
            return true;
        } catch (Throwable tr) {
            return false;
        }
    }

    public void registerActivity(Activity activity) {
        mActivityList.add(activity);
        mHashCodeList.add(activity.hashCode());
    }

    public void unregisterActivity(Activity activity) {
        mActivityList.remove(activity);
        mHashCodeList.remove(Integer.valueOf(activity.hashCode()));
    }

    @Nullable
    public Activity findActivityByHashCode(int hashCode) {
        int index = mHashCodeList.indexOf(hashCode);
        if (index < 0)
            return null;
        return mActivityList.get(index);
    }

    @Nullable
    public Activity getTopActivity() {
        if (!mActivityList.isEmpty()) {
            return mActivityList.get(mActivityList.size() - 1);
        } else {
            return null;
        }
    }
}
